# 首先pip install baidu-aip
# SDK文档链接http://ai.baidu.com/docs#/Face-Python-SDK/top
import base64
import sys

from aip import AipFace

APP_ID = '19017796'
API_KEY = 'ThXUZRcl5OZb3WHa1FccybMQ'
SECRET_KEY = 'CTZK9L1zfebfGPFrPkEczDagDzb5fZHz'

client = AipFace(APP_ID, API_KEY, SECRET_KEY)


def face_check(img_data):
    """
    人脸识别demo
    :param img_data: 二进制的图片数据
    :return:
    """

    data = base64.b64encode(img_data)

    image = data.decode()

    imageType = "BASE64"

    """ 调用人脸检测 """
    client.detect(image, imageType)

    """ 如果有可选参数 """
    options = {}
    options["face_field"] = "beauty,age,faceshape,expression,gender,glasses,landmark"
    options["max_face_num"] = 10

    """ 带参数调用人脸检测 """
    res = client.detect(image, imageType, options)
    try:
        res_list = res['result']
    except Exception as e:
        res_list = None

    return res_list


def mainT(imgPath):
    with open(imgPath, "rb") as f:
        data = f.read()

    res = face_check(data)
    return res


'''
获取五个点的位置 
左眼中心，右眼中心，鼻尖，嘴巴左端点，嘴巴右端点
'''


def get_landmark(img_path):
    """

    :param img_path: 照片路径
    :param gender: 性别"male","female"
    :return:
    """
    re = mainT(img_path)
    landmark_list_male = []
    landmark_list_female = []
    for face_list in re['face_list']:
        landmark_pre = []
        for i in (13, 34, 57, 58, 62):
            mapi = face_list['landmark72'][i]
            landmark_pre.append([mapi['x'], mapi['y']])
        landmark_pre[0][0] = (face_list['landmark72'][17]['x'] + landmark_pre[0][0]) / 2
        landmark_pre[0][1] = (face_list['landmark72'][17]['y'] + landmark_pre[0][1]) / 2
        landmark_pre[1][0] = (face_list['landmark72'][30]['x'] + landmark_pre[1][0]) / 2
        landmark_pre[1][1] = (face_list['landmark72'][30]['y'] + landmark_pre[1][1]) / 2
        if 'male' == face_list['gender']['type']:
            landmark_list_male.append(landmark_pre)
        else:
            landmark_list_female.append(landmark_pre)
    return landmark_list_male, landmark_list_female


if __name__ == '__main__':
    print(get_landmark(sys.argv[1]))
